import {
    request,
    AbstractDiscoverCrawler,
    DiscoverCrawlerTest,
    DiscoverBook,
    DiscoverSource,
    FilterOption,
    FilterCategory,
} from "../../common/common_node.js";


class DiscoverCrawler extends AbstractDiscoverCrawler {

    async filterCategoryList(gender) {

        const url = `${this.source.getPortalUrl(gender)}/store?sz=${gender.name}`;
        const $ = await (await request(url)).doc();
        const selectareaArr = $(".selectview .selectarea");
        const enableSelect = {
            "作品分类": "fc",
            "作品状态": "st",
            "作品字数": "wd",
            "更新时间": "tm"
        }
        const result = [];
        selectareaArr.each(function () {
            const title = $(this).find("h6.title").text();
            const key = enableSelect[title];
            if (!key) {
                return;
            }
            const options = [];
            const aArr = $(this).find("ul li a");
            aArr.each(function () {
                const name = $(this).text().trim();
                const href = $(this).attr("href");
                // 使用正则表达式从href中提取所需的查询参数
                const regex = new RegExp(key + '=([^&]*)');
                const match = href.match(regex);
                const value = match ? decodeURIComponent(match[1]) : null;
                // {name, value}
                options.push(new FilterOption({key: value, name, value}));
            });
            result.push(new FilterCategory({key, name: title, options}))
        });
        return result;
    }

    async bookPage(pageNum, gender, filterParameterList) {

        const filterParams = {};
        for (const filterParameter of filterParameterList) {
            filterParams[filterParameter.key] = filterParameter.optionsValue;
        }

        let url = `${this.source.getPortalUrl(gender)}/store?sz=${gender.name}&page=${pageNum}`;
        for (const key in filterParams) {
            if (!filterParams.hasOwnProperty(key)) {
                continue;
            }
            const value = filterParams[key];
            url += "&" + key + "=" + value
        }
        const $ = await (await request(url)).doc();
        const liArr = $(".store-ul li");
        const bookArr = [];
        liArr.each(function (i, e) {
            bookArr.push(new DiscoverBook({
                name: $(e).find("h3").text().trim(),
                author: $(e).find("span.bkuser-icon").text().trim(),
                intro: $(e).find("p.store-des").text().trim(),
                coverUrl: $(e).find("img.cover").attr("src"),
                type: $(e).find("span.bkcate-icon").text().trim()
            }));
        })

        // 获取所有的页码按钮
        const pageArr = $(".store-paging .cp-wp-page");
        let pages = 1; // 默认设置为1
        if (pageArr && pageArr.length > 0) {
            // 最后一个元素的内容
            const lastPageElem = pageArr.last().find("a");
            const href = lastPageElem.attr("href");
            // 使用正则表达式从href中提取页码
            const regex = /page=(\d+)/;
            const match = href.match(regex);
            if (match) {
                pages = parseInt(match[1], 10);
            }
        }

        return {
            pageNum: pageNum,
            pages: pages,
            list: bookArr
        };
    }

    async hotKeywordList(gender) {
        await super.hotKeywordList(gender);
    }
}

const source = {
    "id": "freebook/shuqi",
    "name": "书旗",
    "active": true,
    "portalUrl": "https://www.shuqi.com",
    "description": null,
    "pageTurningMode": "scroll",
    "enableGenderFilter": true,
    "enableDiscover": true,
    "enableHotKeyword": false
};

await new DiscoverCrawlerTest(new DiscoverCrawler(DiscoverSource.createTestDiscoverSource(source))).run();

